﻿using Bigway.Common.Extensions;
using Bigway.Common.Models.DtoModels;
using Flurl;
using Microsoft.Extensions.Configuration;
using Flurl.Http;
using System.Text.Json;
using System.Text.Encodings.Web;
using System.Text.Unicode;

namespace Bigway.Common.Services;

public class CrmebFrontApiClient(IConfiguration configuration): ICrmebFrontApiClient
{
    private const string DefaultApiBaseUrl = $"https://api.front.jingmeikeji.cc/api/front";
    private readonly string? _apiBaseUrl = configuration.GetValue<string>("CrmebFrontApiBaseUrl");
    private static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions
    {
        Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };

    public async Task<BaseCrmebApiResponseDto<int?>> CallMerchantApplyAsync(
        string name,
        string realName,
        string phone,
        string captcha,
        int categoryId,
        int typeId,
        int handlingFee,
        string? keywords,
        string[] qualificationPictures,
        string address,
        string? remark = null,
        CancellationToken token = default)
    {
        qualificationPictures = qualificationPictures.Select(x => x.AddQuotes())
            .ToArray();
        var joinedQualificationPictures = string.Join(',', qualificationPictures)
            .AddSquareBrackets();
        var apiBaseUrl = _apiBaseUrl ?? DefaultApiBaseUrl;
        var response = await apiBaseUrl.AppendPathSegments("merchant", "settled", "apply")
            .PostJsonAsync(new
            {
                name,
                realName,
                phone,
                captcha,
                categoryId,
                typeId,
                handlingFee,
                keywords,
                address,
                qualificationPicture = joinedQualificationPictures,
                remark,
            }, cancellationToken: token);
        var stringResponse = await response.GetStringAsync();
        return JsonSerializer.Deserialize<BaseCrmebApiResponseDto<int?>>(stringResponse, JsonSerializerOptions)!;
    }
}